const jwt = require("jsonwebtoken")
const cookieKey = "token"

// const serect = "ADMINASSD" // 密钥

// 颁发jwt
/**
 * 
 * @param {*} res 
 * @param {*} maxAge 存活时间
 * @param {*} info  // 信息
 */
exports.award = function(res, info = {}, maxAge = 3600 * 24) {
    const token = jwt.sign(info, process.env.JWT_SERCET, {
            expiresIn: maxAge
        })
        // 添加其他传输
    res.header("authentication", token)
    return token
}


// 验证jwt

exports.verification = function(req) {
    let token = null;
    let authentication = null
    if (req.headers.authentication) {
        authentication = req.headers.authentication.split(" ")
    } else if (req.headers.Authentication) {
        authentication = req.headers.Authentication.split(" ")
    } else if (req.headers.Authorization) {
        authentication = req.headers.Authorization.split(" ")
    } else if (req.headers.authorization) {
        authentication = req.headers.authorization.split(" ")
    } else {
        return null
    }
    // authentication: bearer token

    if (authentication[0].toLowerCase() !== "bearer") {
        return false
    }
    token = authentication[1]
    try {
        const info = jwt.verify(token, process.env.JWT_SERCET)
        return {
            loginId: info.loginId,
            name: info.name,
            id: info.id
        }
    } catch {
        return false
    }

}